<template>
  <view class="addressLibrary_layout">
    <HeadNav :page-name="routeData.type==1? `编辑${routeData.userType === 'seller'?'退货':'收货'}地址`:`添加${routeData.userType === 'seller'?'退货':'收货'}地址`" :borderType="true" :showNav="true"/>
    <div class="address_list_box" :class="{'address_list_box_ios':isIOS}">
      <div class="cozy_box"><img class="img_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/tips1_icon.png" alt="">温馨提示：请确保收件人为真实姓名，否则可能无法收货</div>
      <ul class="address_add_ul">
        <li class="address_add_li">
          <div class="name_box"><i>*</i>姓名：</div>
          <div class="msg_box"><input class="input_box" v-model="name" type="text" maxlength="20" placeholder="请输入姓名"></div>
        </li>
        <li class="address_add_li">
          <div class="name_box"><i>*</i>手机号：</div>
          <div class="msg_box"><input class="input_box" v-model="mobile" type="number" maxlength="15" placeholder="请输入手机号"></div>
        </li>
        <li class="address_add_li" @click.stop="regionPopupShow = true">
          <div class="name_box"><i>*</i>省市区：</div>
          <div class="msg_box msg_box_two">
            <em v-if="provinceStr">{{provinceStr}}</em>
            <span v-else>请选择省市区</span>
            <img class="left_icon_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/jiantou4_icon.png" alt="">
          </div>
        </li>
        <li class="address_add_li">
          <div class="name_box"><i>*</i>详细地址：</div>
          <div class="msg_box">
            <input class="input_box input_box1" v-model="detailedAddress" type="text" maxlength="100" placeholder="请输入详细地址">
            <div class="location_box" hover-class='hover' @click.stop="goToMapFn">
              <img class="location_icon_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/dizhi2_icon.png" alt="">
              <p>定位</p>
            </div>
          </div>
        </li>
      </ul>
      <view class="justify-between supply-section_5">
        <text class="supply-text_5">设为默认地址</text>
        <u-switch
          class="switch-button"
          active-color="#E44435"
          inactive-color="#ccc"
          v-model="isDefaultType"
        ></u-switch>
      </view>
    </div>
    <div class="foot_btn" :class="{'foot_btn_ios':isIOS}">
      <button class="add_btn_box add_btn_box_1" v-if="routeData.type==1" hover-class='hover' @click="deleteAddressFn">删除地址</button>
      <button :disabled="disabledBtn" class="add_btn_box add_btn_box_2" v-else hover-class='hover' @click.stop="getWxAddress">使用微信地址</button>
      <button class="add_btn_box" hover-class='hover' @click="submitAddressFn">保存地址</button>
    </div>
    <addressPick
        :show="regionPopupShow"
        :default-obj="addressConfig"
        @config="configAddress"
        @close="closeAddress"
    />
  </view>
</template>
<script>
import HeadNav from '@/components/headNav/index.vue'
import addressPick from './addressPick';
import request from '@/utils/request/index.js'
import user from "@/api/user.js"
export default {
  components: {
    HeadNav,
    addressPick
  },
  data () {
    return {
      isIOS: uni.getSystemInfoSync().system.indexOf("Android") !== 0,
      isDefaultType: true,
      addressConfig: {
        provinceId: "", // 省ID
        provinceName: "", // 省name
        cityId: "", // 市ID
        cityName: "", // 市name
        countyId: "", // 区ID
        countyName: "", // 区name
      },
      routeData: {},
      regionPopupShow: false,
      provinceStrListArr: [],
      provinceStr: '',
      detailedAddress: '',
      mobile: '',
      name: '',
      disabledType: false,
      disabledBtn: false
    }
  },
  onLoad(r) {
    this.routeData = r
    if (this.routeData.type==1) this.queryEditFn()
  },
  onShow () {
    this.disabledBtn = false
    if (this.$store.state.mapData&&this.$store.state.mapData.location) this.queryCityProperFn()
  },
  methods: {
    queryEditFn () {
      let addressData = this.$store.state.editAddressMsgData
      this.name = addressData.name
      this.mobile = addressData.mobile
      this.detailedAddress = addressData.addr
      this.provinceStr = addressData.provinceName+addressData.cityName+addressData.countyName
      this.isDefaultType = addressData.isDef==1?true:false
      this.addressConfig.provinceId = addressData.provinceId
      this.addressConfig.cityId = addressData.cityId
      this.addressConfig.countyId = addressData.countyId
      this.addressConfig.provinceName = addressData.provinceName
      this.addressConfig.cityName = addressData.cityName
      this.addressConfig.countyName = addressData.countyName
    },
    deleteAddressFn () {
      let this_ = this
      wx.showModal({
        title: '提示',
        cancelText: '取消',
        confirmText: '立即删除',
        confirmColor: '#E34D59',
        content: '是否要删除这个地址？',
        success (res) {
          if (res.confirm) {
            user.deleteAddress({id:this_.$store.state.editAddressMsgData.id}).then(async (res_) => {
              if (res_.code == 200) {
                if (this_.$store.state.choiceAddressData.id&&this_.$store.state.editAddressMsgData.id==this_.$store.state.choiceAddressData.id) {
                  this_.$store.commit('CHOICE_ADDRESS_DATA', {})
                }
                wx.showToast({
                  icon: 'none',
                  mask: true,
                  title: '删除成功!'
                })
                setTimeout(()=>{
                  this_.navigateBack({
                    delta: 1
                  })
                },500)
              }
            })
          } else if (res.cancel) {
          }
        }
      })
    },
    submitAddressFn () {
      if (!this.name) {
        return wx.showToast({
          icon: 'none',
          mask: true,
          title: '请填写姓名!'
        })
      }
      if (!this.mobile) {
        return wx.showToast({
          icon: 'none',
          mask: true,
          title: '请填写手机号!'
        })
      }
      if (!this.provinceStr) {
        return wx.showToast({
          icon: 'none',
          mask: true,
          title: '请选择省市区!'
        })
      }
      if (!this.detailedAddress) {
        return wx.showToast({
          icon: 'none',
          mask: true,
          title: '请填写详细地址!'
        })
      }
      let params = {
        type: this.routeData.userType === 'seller' ? 2 : 1,
        name: this.name,
        mobile: this.mobile,
        isDef: this.isDefaultType?1:0,
        addr: this.detailedAddress,
        provinceId: this.addressConfig.provinceId,
        cityId: this.addressConfig.cityId,
        countyId: this.addressConfig.countyId,
      }
      this.disabledType = true
      if (this.routeData.type==1) {
        params = {
          ...params,
          id: this.$store.state.editAddressMsgData.id
        }
        user.editAddress(params).then(async (res_) => {
          if (res_.code == 200) {
            wx.showToast({
              icon: 'none',
              mask: true,
              title: '编辑成功!'
            })
            setTimeout(()=>{
              this.navigateBack({
                delta: 1
              })
            },1000)
          }
          this.disabledType = false
        })
      } else {
        user.addAddress(params).then(async (res_) => {
          if (res_.code == 200) {
            wx.showToast({
              icon: 'none',
              mask: true,
              title: '保存成功!'
            })
            this.$store.commit("CHOICE_ADDRESS_DATA",res_.data)
            setTimeout(()=>{
              this.navigateBack({
                delta: 1
              })
            },500)
          }
          this.disabledType = false
        })
      }
    },
    queryCityProperFn () {
      user.queryLocation({longitude:this.$store.state.mapData.longitude,latitude:this.$store.state.mapData.latitude}).then(async (res_) => {
        if (res_.code == 200) {
          this.provinceStrListArr = res_.data
          this.provinceStr=''
          this.provinceStrListArr.forEach((pr, i)=>{
            if (pr.level==1) {
              this.addressConfig.provinceId=pr.id
              this.addressConfig.provinceName=pr.name
            }
            if (pr.level==2) {
              this.addressConfig.cityId=pr.id
              this.addressConfig.cityName=pr.name
            }
            if (pr.level==3) {
              this.addressConfig.countyId=pr.id
              this.addressConfig.countyName=pr.name
            }
            this.provinceStr=`${this.provinceStr}${pr.name}`
          })
          // this.queryChoiceAddressFn(this.provinceId,this.cityId,this.countyId)
          this.detailedAddress = this.$store.state.mapData.locationName
        }
      })
    },
    goToMapFn () {
      this.navigateTo({url: '/pages/map/index'})
    },
    configAddress(config) {
      this.addressConfig = config
      this.provinceStr = config.provinceName + config.cityName + config.countyName
      this.provinceId = config.provinceId
      this.cityId = config.cityId
      this.countyId = config.countyId
    },
    closeAddress() {
      this.regionPopupShow = false
    },
    // 获取微信地址
    getWxAddress() {
      this.disabledBtn = true
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.address']) {
            // 地址已授权
            uni.authorize({
              scope: 'scope.address',
              success: () => {
                this._chooseAddress()
              }
            })
          } else {
            // 地址未授权--需要拉起设置授权微信地址
            uni.openSetting({
              success: () => {
                this._chooseAddress()
              }
            })
          }
        }
      })
    },
    // 选择微信地址函数
    _chooseAddress() {
      uni.chooseAddress({
        success: (res) => {
          // console.log(res, '获取微信地址')
          // 字符串地区id
          const nationalCode = res.nationalCode
          // 根据地区id截取反推省级id
          const provinceCode = nationalCode.slice(0, 2)
          // 根据地区id截取反推城市id
          const cityCode = nationalCode.slice(2, 4)
          const addressObj = {
            addr: res.detailInfo,
            cityId: parseInt(provinceCode + cityCode + '00'),
            countyId: parseInt(nationalCode),
            isDef: this.isDefaultType?1:0, // 若原来的地址列表为空时，需要将添加的地址设置为默认地址
            mobile: res.telNumber,
            name: res.userName,
            provinceId: parseInt(provinceCode + '0000'),
            type: this.routeData.userType === 'seller' ? 2 : 1
          }
          // 处理没有地区的城市--例如东莞、中山(只有街道之类的，即6位行政区编码最后两位均为00)
          const countyCode = nationalCode.slice(4, 6)
          if (countyCode === '00') {
            addressObj.countyId = parseInt(res.nationalCodeFull)
          }
          user.addAddress(addressObj).then(result => {
            if (result.code === 200) {
              uni.showToast({
                icon: 'none',
                mask: true,
                title: '地址添加成功!'
              })
              // 若原来的地址列表为空时，将添加的地址添加到vuex中(即默认地址)
              this.$store.commit('CHOICE_ADDRESS_DATA', result.data)
              setTimeout(()=>{
                this.navigateBack({
                  delta: 1
                })
              },500)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.addressLibrary_layout {
  width: 100vw;
  height: 100vh;
  background-color: #F2F3F5;
  .address_list_box {
    width: 100%;
    height: calc(100vh - 179px);
    &.address_list_box_ios {
      height: calc(100vh - 209px);
    }
    .cozy_box {
      padding: 6rpx 32rpx;
      background: #fffbe8;
      font-size: 24rpx;
      color: #FAAB0C;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      .img_box {
        width: 32rpx;
        height: 32rpx;
        margin-right: 8rpx;
      }
    }
    .address_add_ul {
      background-color: #fff;
      padding-bottom: 30rpx;
      .address_add_li {
        display: flex;
        align-items: center;
        flex: 1;
        padding: 26rpx 32rpx;
        .name_box {
          width: 156rpx;
          flex: 0 0 auto;
          display: flex;
          align-items: center;
          font-size: 28rpx;
          color: #323233;
          i {
            color: #E44435;
          }
        }
        .msg_box {
          width: 520rpx;
          position: relative;
          &.msg_box_two {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #969799;
            em {
              color: #323233;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
          .input_box {}
          .input_box1 {
            width: 468rpx;
          }
          .left_icon_box {
            width: 32rpx;
            height: 32rpx;
          }
          .location_box {
            position: absolute;
            right: 0;
            top: 0;
            .location_icon_box {
              display: block;
              width: 32rpx;
              height: 32rpx;
              margin: 0 auto 0;
            }
            p {
              font-size: 20rpx;
              color: #969799;
            }
          }
        }
      }
    }
    .supply-section_5 {
      display: flex;
      align-items: center;
      margin-top: 20rpx;
      padding: 26rpx 32rpx;
      background-color: #fff;
    }
  }
  .foot_btn {
    padding: 30rpx 32rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    &.foot_btn_ios {
      padding: 30rpx 32rpx 60rpx 32rpx;
    }
    .add_btn_box {
      width: 100%;
      height: 88rpx;
      background: #e44435;
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #fff;
      &.add_btn_box_1{
        border: 2rpx solid #e44435;
        border-radius: 46rpx;
        box-sizing: border-box;
        color: #E44435;
        background: none;
        margin-bottom: 32rpx;
      }
      &.add_btn_box_2{
        background-color: $n9Color;
        border: 2rpx solid $n9Color;
        border-radius: 46rpx;
        box-sizing: border-box;
        color: #FFF;
        margin-bottom: 32rpx;
      }
    }
  }
}
.fixed_box {
  .picker_con {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    background: #fff;
    &.picker_con_ios {
      padding-bottom: 40rpx;
    }
    .title_box {
      width: 100%;
      height: 92rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      span {
        position: absolute;
        right: 0;
        top: 0;
        display: inline-block;
        width: 92rpx;
        height: 92rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 32rpx;
          height: 32rpx;
        }
      }
    }
    .btn_box_save {
      padding: 20rpx 30rpx;
      &.btn_box_save_ios {
        padding: 20rpx 30rpx 50rpx;
      }
      .red_btn {
        width: 100%;
        height: 104px;
      }
    }
    .btn_listBox {
      display: flex;
      width: 100%;
      height: 112rpx;
      border-top: 2rpx solid #F7F8FA;
      &.btn_listBox_ios {
        padding: 0 0 46rpx 0;
      }
      .white_btn {
        width: 50%;
        height: 100%;
        border: none;
        border-radius: 0;
      }
      .white_btn2 {
        border-left: 2rpx solid #F7F8FA;
        color: #E44435;
      }
    }
  }
  .publicPopup_box {
    .weui-cell {
      margin: 64rpx 0;
      padding-bottom: 16rpx;
      border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
      .weui-input {
        font-size: 32rpx;
        font-weight: 400;
        color: #000000;
        line-height: 44rpx;
      }
    }
    .red_btn {
      width: 100%;
      height: 88rpx;
    }
    .red_btn1 {
      color: #FFFFFF;
      opacity: 0.6;
    }
  }
}
</style>
